package com.google.code.virtualhockey.vhx.sds.fields

import com.google.code.virtualhockey.vhx.sds._
import com.google.appengine.api.datastore.ShortBlob
import com.google.appengine.api.datastore.Blob

/**
 * Long byte array with a maximum length of 1 MB. Cannot be indexed.
 */
class SLongBlob( parent: STMetaData[_],
                 name: String,
                 dbName: Option[String] = None ) extends SField( parent, name, false, dbName ) {

  protected type TRawType = Array[Byte]
  protected type TGaeType = Blob
  protected val _clsRaw = classOf[TRawType]
  protected val _clsGae = classOf[TGaeType]
  override protected[sds] val _showInToString: Boolean = false

  override protected def validate( value: Option[TRawType] ): Unit = {
    if ( value != None && value.get.length > 1024 * 1024 )
      sys.error( "A byte array persisted as long Blob cannot be longer than " + 1024 * 1024 + " bytes." )
  }

  override protected[sds] def convertGaeToSds( value: TGaeType ): TRawType = {
    value.getBytes
  }

  override protected[sds] def convertSdsToGae( value: TRawType ): TGaeType = {
    new Blob( value )
  }
}

/**
 * Short byte array with a maximum length of 512 bytes.
 */
class SShortBlob( parent: STMetaData[_],
                  name: String,
                  indexed: Boolean = false,
                  dbName: Option[String] = None ) extends SField( parent, name, indexed, dbName ) {

  protected type TRawType = Array[Byte]
  protected type TGaeType = ShortBlob
  protected val _clsRaw = classOf[TRawType]
  protected val _clsGae = classOf[TGaeType]
  override protected[sds] val _showInToString: Boolean = false

  override protected def validate( value: Option[TRawType] ): Unit = {
    if ( value != None && value.get.length > 512 )
      sys.error( "A byte array persisted as short Blob cannot be longer than " + 512 + " bytes." )
  }

  override protected[sds] def convertGaeToSds( value: TGaeType ): TRawType = {
    value.getBytes
  }

  override protected[sds] def convertSdsToGae( value: TRawType ): TGaeType = {
    new ShortBlob( value )
  }
}
